package com.dot.comm.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Arrays;

/**
 * @author xxkk
 * @version 1.0.0
 * @title ImageSegmentation
 * @description ʕ•ᴥ•ʔ 图片分割
 * @create 2024/10/12 08:57
 **/
public class ImageSegmentation {

    public static BufferedImage SplitPicture(BufferedImage image, int x, int y, int blockSize) {
//        BufferedImage[] res = new BufferedImage[2];
        BufferedImage sub = image.getSubimage(x, y, blockSize, blockSize);
        BufferedImage sub1 = copyImage(sub);
        int gray = 12; // 灰色，这里假设是中等灰度
        int[] pixelData = new int[blockSize * blockSize];
        Arrays.fill(pixelData, gray);
        image.setRGB(x, y, blockSize, blockSize, pixelData, 0, blockSize);
        return sub1;
    }

    private static BufferedImage copyImage(BufferedImage sub) {
        BufferedImage dis = new BufferedImage(sub.getWidth(), sub.getHeight(), sub.getType());
        copySrcIntoDstAt(sub, dis,0,0);
        return dis;
    }

    private static void copySrcIntoDstAt(
            final BufferedImage src,
            final BufferedImage dst,
            final int dx,
            final int dy
    ) {
        for (int x = 0; x < src.getWidth(); x++) {
            for (int y = 0; y < src.getHeight(); y++) {
                dst.setRGB(dx + x, dy + y, src.getRGB(x, y));
            }
        }
    }

    public static void main(String[] args) {
        try {
            String fileName = "001.png";
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream(fileName);
            BufferedImage image = ImageIO.read(inputStream);
            //        int w = image.getWidth();
            //        int h = image.getHeight();
            int block = 200;
            BufferedImage sub = ImageSegmentation.SplitPicture(image, 10, 10, block);
            String outFileName = "sub.png";
            String out1 = "sub_001.png";
//            System.getProperty("user.dir");
            String resourcePath = classLoader.getResource("").getPath();
            BufferedOutputStream out1_ = new BufferedOutputStream(new FileOutputStream(resourcePath + out1));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(resourcePath + outFileName));
            ImageIO.write(sub, "png", out);
            ImageIO.write(image, "png", out1_);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
